package com.tidc.seaservermodel.util;

import com.alibaba.fastjson.JSONArray;
import com.tidc.seaservermodel.entity.Fres;
import com.tidc.seaservermodel.exception.TidcBadParent;
import com.tidc.seaservermodel.exception.TidcRestException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author ：冯涛滔
 * @date ：Created in 2020/10/6 17:41
 * @description：请求工具类
 * @modified By：
 * @version:
 */
@Component
public class RestUtil {
    @Resource
    private HttpHeaders httpHeaders;
    @Resource
    private RestTemplate restTemplate;

    /**
     * 请求头 使用自定义的 内有专属密码 使用的是json传输
     * @param object
     * @param url
     * @param uri 第一个位置不加斜杠
     * @param <T>
     * @throws TidcRestException
     */
    public <T> Fres post(T object,String url,String uri) throws TidcRestException {
        Object json = JSONArray.toJSON(object);
        HttpEntity<String> req = new HttpEntity(json.toString(), httpHeaders);
        Fres response = restTemplate.postForObject( url+uri
                ,req,Fres.class);
        if (response!=null && response.getMeta().getStatus()!=200) {
            throw new TidcRestException(response.getMeta().getMessage());
        }
        if(response == null){
            throw new TidcRestException("请求未被响应 返回值为空 url为" + url + "请求体为" + object);

        }
        return response;
    }
}
